#include "local.h"
#include "config.h"


#define MAX_LENGTH 200
#define PARAM_MAX_LENGTH 100
#define VALUE_MAX_LENGTH 100

IConfig	*CreateConfig ( IConsole *con, const char *cfg_name )
{
	return new EConfig ( con, cfg_name );
}



EConfig::EConfig ( IConsole *con, const char *cfg_name )
{
	this->cfg_name = cfg_name;
	this->con = con;

	Init();


}




EConfig::~EConfig ( void )
{
	params.clear();
}



void EConfig::Init ( void )
{
	FILE *file = fopen(cfg_name.c_str(), "r");
	if ( !file )
	{
		con->Logf("Can't read configuration file: %s", cfg_name.c_str());
		return;
	}

	int position = 0;
	int lines = 0;

	EParam_s param;

	char	**buffer = new char *[10];
	for ( int i = 0; i < 10; i++ )
	{
		buffer[i] = new char [MAX_LENGTH];
	}

	while(!feof(file))
	{

		fgets(buffer[lines], MAX_LENGTH, file);
		lines++;
	}

	fclose(file);

	for ( int i = 0; i < lines; i++ )
	{
		position = 0;
		while(buffer[i][position] && buffer[i][position] != '=')
		{
			position++;
		}

		if	(position)
		{
			char	*name_param = new char[10];
			char	*value = new char[20];
			strncpy(name_param, buffer[i], position);
			name_param[position]='\0';
			strcpy(value, buffer[i] + position +1);

			param.name = name_param;
			param.value = value;
			params.push_back(param);

			delete name_param;
			delete value;
			//con->Logf("%s=%s",param.name.c_str(), param.value.c_str());
		}


	}

	for ( int i = 0; i < 10; i++ )
	{
		delete buffer[i];
	}
	delete []buffer;

//	while(!feof(file))
//	{
//		position = 0;
//		fgets(buffer, MAX_LENGTH, file);
//		//fscanf(file, "%s", buffer);
//		while ( buffer[position] && buffer[position] != '=') {
//			position++;
//		}
//
//		if (position)
//		{
//			name_param = (char *) malloc(position);
//			value = (char *) malloc(strlen(buffer) - position);
//			memcpy(name_param, buffer, position);
//			strcpy(value, buffer + position + 1);
//
//
//			param.name = name_param;
//			param.value = value;
//			params.push_back(param);
//			lines++;
//
//			con->Log(name_param);
//		}
//	}


	//fclose(file);

}



const char *EConfig::GetField ( const char *field_name )
{

	for ( uint i = 0; i < params.size(); i++ )
	{
		if ( strcmp(params[i].name.c_str(), field_name) == 0 )
		{
			return params[i].value.c_str();
		}
	}

	return "0";
}



void EConfig::SetFiled ( const char *field_name, const char *value )
{

}
